"""
Author        yongfa
Date          2022-07-18 15:01:10
LastEditTime  2022-07-21 14:05:52
LastEditors   yongfa
Description   业务处理
"""
from flask import request
from app.extensions.services import SimpleService
from app.extensions.fileHelper.upload import Uploader
from app.extensions.exception import Success, Failed
from app.extensions.sqlalchemy import pagination_to_dict


class UploaderService(SimpleService):

    def upload(self):
        module_name = self.args.get('module_name')
        files = request.files.getlist('file')
        data = {'file_path': [], 'file_small_path': []}
        uploader = Uploader()
        for file in files:
            file_info = uploader.upload_files(module_name=module_name, file=file)
            data['file_path'].append(file_info['file_path'])
            data['file_small_path'].append(file_info['file_small_path'])
            # 保存到数据库, 截断地址
            file_info['file_path'] = uploader.cut_path(file_info['file_path'])
            file_info['file_small_path'] = uploader.cut_path(file_info['file_small_path'])
            self.model.create(**file_info)

        return Success(data)

    def delete(self):
        file_ids = self.args.get('file_ids')
        files = self.model.query.filter(self.model.id.in_(file_ids)).all()
        if not files:
            return Failed(message='文件不存在')
        uploader = Uploader()
        for file in files:
            file.hard_delete()
            uploader.delete_files([file.file_path])

        return Success()

    def get_list(self):

        page = self.args.get('page')
        size = self.args.get('size')
        file_cate = self.args.get('module_name')
        name = self.args.get('name')
        queryset = self.model.query.filter().order_by(self.model.id.desc())
        if file_cate is not None:
            queryset = queryset.filter(self.model.file_cate == file_cate)

        if name is not None:
            queryset = queryset.filter(self.model.name.ilike("%{}%".format(name)))

        paginator = queryset.paginate(page=page, per_page=size, error_out=True)
        result = pagination_to_dict(paginator)
        return Success(result=result)

    def get_detail(self, id):
        item = self.model.get_or_404(id=id)
        return Success(item)
